<template>
  <div class="mine-edit">
    <!--
        router.go(负数)       router.go(-1)返回上一个页面   router.back()
        router.go(0)          router.go(0)刷新页面
        router.go(正数)       router.go(1) 下一个页面      router.forward()
     -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.push('/mine')"
    ></van-nav-bar>
    <van-uploader :afterRead="afterRead">
      <div class="img">
        <img class="avatar" :src="userInfo.photo" alt="" />
      </div>
    </van-uploader>

    <van-cell-group>
      <van-cell
        title="名称"
        :value="userInfo.name"
        is-link
        @click="nameClick"
      ></van-cell>
      <!-- 0 ：男   1:女  2：保密
            const obj={0:'男',1:'女',2:'保密'}
            obj[1]
            const gender=1
            obj[gender]
            {0:'男',1:'女',2:'保密'}[gender]
    -->
      <van-cell
        @click="showGender = true"
        title="性别"
        :value="{ 0: '男', 1: '女' }[userInfo.gender]"
        is-link
      ></van-cell>
      <van-cell
        @click="birthdayClick"
        title="生日"
        :value="userInfo.birthday"
        is-link
      ></van-cell>
    </van-cell-group>

    <!-- 修改名称弹框
    1:显示姓名
    2：控制弹框打开
    3：弹框内的输入框有一个聚焦处理
    4：点击确定要调用接口实现修改
        a:定义接口api
        b:导入与调用接口
        c:调用成功
           提示
           更新一下vuex内部的用户信息

    -->
    <van-dialog
      title="修改名称"
      v-model="showName"
      show-cancel-button
      @confirm="nameConfirm"
    >
      <van-field v-model.trim="nameVal" ref="field"></van-field>
    </van-dialog>

    <!-- 性别修改弹框
       1:点击性别控制弹框打开
       2：显示控制（如果是女，只需要显示男，如果是男，只需要显示女）
       3：点击取消：关闭弹框
       4：点击cell性别 ，修改性别

    -->
    <van-popup v-model="showGender" position="bottom">
      <van-nav-bar
        title="修改性别"
        left-text="取消"
        @click-left="showGender = false"
      ></van-nav-bar>
      <van-cell
        @click="genderClick(0)"
        v-if="userInfo.gender === 1"
        title="男"
        is-link
      ></van-cell>
      <van-cell @click="genderClick(1)" v-else title="女" is-link></van-cell>
    </van-popup>
    <!-- 生日修改
    1:按钮控制打开
    2:时间的显示渲染
    2：点击确定按钮调用接口
    3：调用成功：
         提示
         更新vuex
         关闭弹框

    -->
    <van-popup v-model="showBirthday" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showBirthday = false"
        @confirm="birthdayConfirm"
      />
    </van-popup>
    <!-- 头像上传裁切 -->
    <div class="corp" v-if="showImg">
      <VueCropper
        :img="img"
        autoCrop
        autoCropWidth="200"
        autoCropHeight="200"
        ref="cropper"
      ></VueCropper>

      <div class="btn">
        <van-button type="primary" @click="uploadImg">裁剪</van-button>
        <van-button type="primary" @click="showImg = false">取消</van-button>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { userProfilePatch, userPhoto } from '@/api/mine'
import dayjs from 'dayjs'
import { VueCropper } from 'vue-cropper'
export default {
  components: {
    VueCropper
  },
  data () {
    return {
      showName: false,
      nameVal: '',
      showGender: false,
      showBirthday: false,
      currentDate: new Date(),
      minDate: new Date('1970/01/01'),
      maxDate: new Date(),
      showImg: false,
      img: ''
    }
  },
  async created () {
    // 获取用户信息
    this.$store.dispatch('user/getUserInfo')
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  methods: {
    nameClick () {
      // 打开弹框
      this.showName = true
      // 修改显示姓名
      this.nameVal = this.userInfo.name
      // 打开弹框时聚焦
      setTimeout(() => {
        this.$refs.field.focus()
      }, 600)
    },
    // 确定修改name
    async nameConfirm () {
      // 1：无值，2：无修改
      if (this.nameVal === '' || this.nameVal === this.userInfo.name) return
      await userProfilePatch({
        name: this.nameVal
      })
      // 提示
      this.$toast.success('修改成功')
      // 更新用户信息
      this.$store.commit('user/setUserInfo', {
        ...this.userInfo,
        name: this.nameVal
      })
    },
    // 性别点击修改
    async genderClick (val) {
      await userProfilePatch({
        gender: val
      })
      // 提示
      this.$toast.success('修改成功')
      // 更新用户信息
      this.$store.commit('user/setUserInfo', {
        ...this.userInfo,
        gender: val
      })
      // 关闭弹框
      this.showGender = false
    },
    // 生日点击
    birthdayClick () {
      // 打开弹框
      this.showBirthday = true
      // 渲染当前生日
      this.currentDate = new Date(this.userInfo.birthday)
    },
    // 生日确定
    async birthdayConfirm () {
      if (
        dayjs(this.currentDate).format('YYYY-MM-DD') === this.userInfo.birthday
      ) {
        return
      }
      await userProfilePatch({
        birthday: dayjs(this.currentDate).format('YYYY-MM-DD')
      })
      // 提示
      this.$toast.success('修改成功')
      // 更新用户信息
      this.$store.commit('user/setUserInfo', {
        ...this.userInfo,
        birthday: dayjs(this.currentDate).format('YYYY-MM-DD')
      })
      // 关闭弹框
      this.showBirthday = false
    },
    // 头像上传
    afterRead (res) {
      // 显示裁切
      this.showImg = true
      this.img = res.content
      console.log(res)
    },
    // 上传头像
    async uploadImg () {
      this.$refs.cropper.getCropBlob(async data => {
        // do something
        console.log(data)
        const f = new FormData()
        f.append('photo', data)
        const res = await userPhoto(f)
        // 提示
        this.$toast.success('更新头像成功')
        // 修改vuex数据
        this.$store.commit('user/setUserInfo', {
          ...this.userInfo,
          photo: res.data.photo
        })
        // 关闭弹框
        this.showImg = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
.mine-edit {
  .img {
    width: 100vw;
    padding: 15px;
    text-align: center;
    box-sizing: border-box;
    .avatar {
      width: 143px;
      height: 143px;
      border-radius: 50%;
      object-fit: cover;
    }
  }
  .corp {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    background-color: #7f7f7f;
    .btn {
      position: absolute;
      bottom: 0;
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
